package cn.angis.system.controller;


import cn.angis.common.model.R;
import cn.angis.db.controller.RBaseController;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缓存监控
 *
 * @author ruoyi
 */
@Controller
@Mapping("/monitor/cache")
public class CacheController extends RBaseController {
    @Inject
    private RedisClient client;

    @Inject
    private RedissonClient redissonClient;


    @Mapping
    @Get
    public R<Map<String, Object>> getInfo() throws Exception {
        Map<String, Object> info = client.connect().sync(StringCodec.INSTANCE, RedisCommands.INFO_ALL);
        Map<String, Object> commandStats = client.connect().sync(StringCodec.INSTANCE, RedisCommands.INFO_COMMANDSTATS);
        long dbSize = client.connect().sync(StringCodec.INSTANCE, RedisCommands.DBSIZE);

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.keySet().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.get(key).toString();
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return success(result);
    }

    @Mapping("/list")
    @Get
    public R<Map<String, Object>> cache() {
        List<String> keys = client.connect().sync(StringCodec.INSTANCE, RedisCommands.KEYS, "*");
        Map<String, Object> result = new HashMap<>(2);
        for (String key : keys) {
            try {
                Object value = client.connect().sync(StringCodec.INSTANCE, RedisCommands.GET, key);
                result.put(key, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return success(result);
    }

}
